package com.dlz.systemshop.controller;


import com.dlz.systemshop.pojo.APIResponse;
import com.dlz.systemshop.pojo.Category;
import com.dlz.systemshop.service.CategoryService;
import com.dlz.systemshop.utils.UpLoadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private UpLoadUtil upLoadUtil;

    @GetMapping("/deleteById")
    public APIResponse<Void> deleteById(int id) {
        categoryService.deleteById(id);
        return APIResponse.success(null);
    }

    @GetMapping("/list")
    public APIResponse<List<Category>> list() {
        List<Category> categories = categoryService.findAll();
        for (Category category : categories) {
            Integer pid = category.getPid();
            for(Category categoryIn : categories) {
                if(categoryIn.getId().equals(pid)){
                    category.setPname(categoryIn.getName());
                    break;
                }
            }
        }
        return APIResponse.success(categories);
    }

    @GetMapping("/findById")
    public APIResponse<Category> findById(int id) {
        Category category = categoryService.findByid(id);
        return APIResponse.success(category);
    }

    @PostMapping("/add")
    public APIResponse<Void> add(@RequestBody Category category) {
        categoryService.save(category);
        return APIResponse.success(null);
    }
    @PostMapping("/update")
    public APIResponse<Void> update(@RequestBody Category category) {
        categoryService.update(category);
        return APIResponse.success(null);
    }

    @PostMapping("/uploadImage")
    public APIResponse<String> uploadImage(@RequestParam("file") MultipartFile file) {
        String filePath = upLoadUtil.uploadImage(file,"upload/image/category/myAdd");
        return APIResponse.success( filePath);
    }

}
